package com.bjpowernode.web.service;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.constants.Constant;
import com.bjpowernode.web.config.TencentRealNameConfig;
import com.bjpowernode.web.util.RealNameUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author 麦翔盛
 * @ClassName: RealNameService
 * @Package: com.bjpowernode.web.service
 * @description: 实名认证 服务类
 * @date 2022/5/24 19:37
 */
@Service
public class RealNameService {


    @Resource
    private TencentRealNameConfig tencentRealNameConfig;

    /**
     * @param realName 真实名称
     * @param cardNo   身份id
     * @return 身份是否通过
     */
    public boolean verifiedRealName(String realName, String cardNo) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        boolean flag = false;
        //获取秘钥
        String secretKey = tencentRealNameConfig.getSecretKey();
        String secretId = tencentRealNameConfig.getSecretId();
        //获取实名认证的结果
        String resultStr = RealNameUtils.identifyRealName(secretId, secretKey, realName, cardNo);

        //解析结果
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        Object successObj = jsonObject.get("success");
        boolean success = (boolean) successObj;
        JSONObject data = jsonObject.getJSONObject("data");
        //如果身份证的格式正确就能解析出data json
        if (data != null && success) {
            //获取是否一致的位置 如果为0表示一致 其他不一致
            Object resultObj = data.get("result");
            int result = (int) resultObj;
            System.out.println(result);
            if (result == Constant.ID_CONSISTENT_RESULT){
                flag = true;
            }
        }

        return flag;
    }
}
